import { Hono } from 'hono'
import { z } from 'zod'
import { AdvancedSecurityService } from '@/services/advancedSecurityService'
import { getCurrentUser } from '@/middleware/auth'
import { asyncHandler, ValidationError } from '@/middleware/errorHandler'

const advancedSecurity = new Hono()
const securityService = new AdvancedSecurityService()

// 验证模式
const scanRequestSchema = z.object({
  versionId: z.string().uuid(),
  scanTypes: z.array(z.enum(['vulnerability', 'malware', 'dependency', 'code_quality', 'license'])).optional()
})

const policySchema = z.object({
  name: z.string().min(3).max(100),
  description: z.string().max(500),
  rules: z.array(z.object({
    id: z.string(),
    type: z.enum(['file_pattern', 'code_pattern', 'dependency_check', 'size_limit', 'permission_check']),
    pattern: z.string(),
    action: z.enum(['allow', 'warn', 'block']),
    severity: z.enum(['low', 'medium', 'high', 'critical']),
    message: z.string()
  })),
  enabled: z.boolean().default(true)
})

// 验证中间件
const validateJson = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const body = await c.req.json()
      const validatedData = schema.parse(body)
      c.set('validatedData', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError(`Invalid request body: ${error.errors.map(e => e.message).join(', ')}`)
      }
      throw error
    }
  }
}

// 执行综合安全扫描 (管理员功能)
advancedSecurity.post('/scan/comprehensive',
  getCurrentUser,
  validateJson(scanRequestSchema),
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以执行安全扫描
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const { versionId } = c.get('validatedData')
    
    const results = await securityService.performComprehensiveScan(versionId)
    
    return c.json({
      success: true,
      data: { results },
      message: 'Comprehensive security scan completed'
    })
  })
)

// 获取扫描历史
advancedSecurity.get('/scan/history/:versionId',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    const versionId = c.req.param('versionId')
    
    // 管理员或插件开发者可以查看扫描历史
    if (user.role !== 'admin') {
      // 这里可以添加检查用户是否是插件开发者的逻辑
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Access denied' }
      }, 403)
    }

    const history = await securityService.getScanHistory(versionId)
    
    return c.json({
      success: true,
      data: { history },
      message: 'Scan history retrieved'
    })
  })
)

// 获取安全统计 (管理员功能)
advancedSecurity.get('/stats',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以查看安全统计
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const stats = await securityService.getSecurityStats()
    
    return c.json({
      success: true,
      data: stats,
      message: 'Security statistics retrieved'
    })
  })
)

// 创建安全策略 (管理员功能)
advancedSecurity.post('/policies',
  getCurrentUser,
  validateJson(policySchema),
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以创建安全策略
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const policyData = c.get('validatedData')
    
    const policy = await securityService.createSecurityPolicy(policyData)
    
    return c.json({
      success: true,
      data: { policy },
      message: 'Security policy created successfully'
    })
  })
)

// 应用安全策略 (管理员功能)
advancedSecurity.post('/policies/:policyId/apply',
  getCurrentUser,
  validateJson(z.object({ versionId: z.string().uuid() })),
  asyncHandler(async (c) => {
    const user = c.get('user')
    const policyId = c.req.param('policyId')
    const { versionId } = c.get('validatedData')
    
    // 只有管理员可以应用安全策略
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const result = await securityService.applySecurityPolicy(versionId, policyId)
    
    return c.json({
      success: true,
      data: { result },
      message: 'Security policy applied successfully'
    })
  })
)

// 获取威胁情报摘要 (管理员功能)
advancedSecurity.get('/threat-intelligence',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以查看威胁情报
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    // 这里可以集成真实的威胁情报源
    const threatIntelligence = {
      lastUpdated: new Date(),
      sources: ['Internal DB', 'CVE Database', 'Malware Signatures'],
      totalIndicators: 15420,
      recentThreats: 23,
      criticalAlerts: 3,
      summary: {
        malwareHashes: 8500,
        suspiciousDomains: 3200,
        knownVulnerabilities: 2800,
        maliciousPatterns: 920
      }
    }
    
    return c.json({
      success: true,
      data: threatIntelligence,
      message: 'Threat intelligence summary retrieved'
    })
  })
)

// 手动触发特定类型扫描 (管理员功能)
advancedSecurity.post('/scan/:scanType',
  getCurrentUser,
  validateJson(z.object({ versionId: z.string().uuid() })),
  asyncHandler(async (c) => {
    const user = c.get('user')
    const scanType = c.req.param('scanType')
    const { versionId } = c.get('validatedData')
    
    // 只有管理员可以执行扫描
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    // 验证扫描类型
    const validScanTypes = ['vulnerability', 'malware', 'dependency', 'code_quality', 'license']
    if (!validScanTypes.includes(scanType)) {
      return c.json({
        success: false,
        error: { code: 'INVALID_SCAN_TYPE', message: 'Invalid scan type' }
      }, 400)
    }

    // 执行特定类型的扫描
    const results = await securityService.performComprehensiveScan(versionId)
    const specificResult = results.find(r => r.scanType === scanType)
    
    return c.json({
      success: true,
      data: { result: specificResult },
      message: `${scanType} scan completed`
    })
  })
)

// 获取安全扫描报告 (管理员功能)
advancedSecurity.get('/reports/security/:versionId',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    const versionId = c.req.param('versionId')
    
    // 只有管理员可以查看安全报告
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const history = await securityService.getScanHistory(versionId)
    
    // 生成综合报告
    const report = {
      versionId,
      generatedAt: new Date(),
      totalScans: history.length,
      latestScans: history.slice(0, 5),
      summary: {
        overallStatus: history.length > 0 ? history[0].result : 'not_scanned',
        criticalIssues: history.reduce((count, scan) => 
          count + scan.findings.filter(f => f.severity === 'critical').length, 0),
        highIssues: history.reduce((count, scan) => 
          count + scan.findings.filter(f => f.severity === 'high').length, 0),
        mediumIssues: history.reduce((count, scan) => 
          count + scan.findings.filter(f => f.severity === 'medium').length, 0),
        lowIssues: history.reduce((count, scan) => 
          count + scan.findings.filter(f => f.severity === 'low').length, 0)
      },
      recommendations: [
        'Review all critical and high severity findings',
        'Implement security best practices',
        'Regular security scanning recommended',
        'Keep dependencies up to date'
      ]
    }
    
    return c.json({
      success: true,
      data: { report },
      message: 'Security report generated'
    })
  })
)

export default advancedSecurity
